import Vue from 'vue';

/**
 * 自定义防抖指令：只能用在原生按钮上
 * 用法：
 *  1带参写法:
 *  <button v-debounce:方法名称="参数">
 *  2.无需带参:
 *  <button v-debounce:方法名称>;
 *  <button v-debounce="方法名称">
 *
 * */
const debounce = Vue.directive('debounce', {
  inserted: function (el, binding, vnode) {
    const { arg, value } = binding;
    const that = vnode.context;
    let timer;
    el.addEventListener('click', () => {
      if (timer) {
        clearTimeout(timer);
      }
      timer = setTimeout(() => {
        arg ? that[arg](value) : value();
      }, 300);
    });
  }
});

export default debounce;
